<template>
  <div>
    <el-dialog
      :append-to-body="false"
      :close-on-click-modal="false"
      :modal="false"
      @close="closeQrCodeInterval"
      center
      custom-class="login-dialog"
      v-model="visible"
      width="350px">
      <!-- 登录界面 -->
      <div class="loginDialog" v-if="loginPage === 0">
        <div @click="toQrCodePage" class="qrCode">
          <el-tooltip class="item" content="扫码登录更安全" effect="dark" placement="right">
            <img
              class="white-filter"
              height="52"
              src="https://p6.music.126.net/obj/wo3DlcOGw6DClTvDisK1/9656441793/9f07/c197/3af2/f07b8d6ef20964be159ce812841fc9d2.png"
              width="52"/>
          </el-tooltip>
        </div>
        <div class="login-box login-box-center">
          <el-avatar :src="wyyyyIcon" style="width: 100px; height: 100px"></el-avatar>
          <div class="login-form">
            <el-form :model="loginUser">
              <el-form-item>
                <el-input
                  placeholder="请输入手机号"
                  v-model="loginUser.phone">
                  <template #prepend>
                    <el-icon :size="15">
                      <Iphone/>
                    </el-icon>
                  </template>
                </el-input>
              </el-form-item>
              <el-form-item>
                <el-input
                  placeholder="请输入密码"
                  v-model="loginUser.password"
                  v-show="!isCodeLogin">
                  <template #prepend>
                    <el-icon :size="15">
                      <Lock/>
                    </el-icon>
                  </template>
                </el-input>
                <el-input
                  placeholder="请输入验证码"
                  v-model="loginUser.code"
                  v-show="isCodeLogin">
                  <i class="el-input__icon el-icon-key" slot="prefix"
                     style="transform: rotateX(180deg);"></i>
                  <el-button @click="sendCode" slot="append">{{ isCountDown && second > 0 ? second :
                    '获取验证码' }}
                  </el-button>
                </el-input>
              </el-form-item>
              <div>
                <el-row align="middle" style="margin: 10px 0">
                  <el-col :span="6">
                    <el-checkbox>
                      <span style="font-size: 12px">自动登录</span>
                    </el-checkbox>
                  </el-col>
                  <el-col :span="18">
                    <div style="float: right">
                      <el-link class="forget-login" type="primary">忘记密码</el-link>
                      <el-divider direction="vertical"></el-divider>
                      <el-link @click="code2email" class="forget-login" type="primary"
                               v-show="isCodeLogin">验证码登录
                      </el-link>
                      <el-link @click="email2code" class="forget-login" type="primary"
                               v-show="!isCodeLogin">密码登录
                      </el-link>
                    </div>
                  </el-col>
                </el-row>
              </div>
              <el-form-item>
                <div style="margin-top: 20px; width: 100%">
                  <el-button @click="loginByPhone" style="width: 100%;" type="danger">
                    登录
                  </el-button>
                </div>
              </el-form-item>
              <div>
                <div class="login-form-summary">
                  <el-link @click="loginByAnonymous" target="_blank">游客登录</el-link>
                  <el-divider direction="vertical"></el-divider>
                  <el-link href="https://element.eleme.io" target="_blank">注册</el-link>
                </div>
              </div>
            </el-form>
          </div>
          <!-- 社交登录 -->
          <div class="social-icons">
            <div class="social-icon">
              <i class="spring social-wx"></i>
            </div>
            <div class="social-icon">
              <i class="spring social-qq"></i>
            </div>
            <div class="social-icon">
              <i class="spring social-weibo"></i>
            </div>
            <div @click="loginPage = 2" class="social-icon">
              <i class="spring social-163email"></i>
            </div>
          </div>
        </div>

        <!-- 服务条款 -->
        <div class="terms-service">
          <el-checkbox></el-checkbox>
          <span style="margin-left: 8px;">同意</span>
          <el-link class="terms-service-text" type="primary">《服务条款》</el-link>
          <el-link class="terms-service-text" type="primary">《隐私政策》</el-link>
          <el-link class="terms-service-text" type="primary">《儿童隐私政策》</el-link>
        </div>
      </div>
      <!-- 扫码登录 -->
      <div class="qrCodeDialog" v-if="loginPage === 1">
        <div class="qrcode-text">扫码登录</div>
        <!-- 由于加了滤镜，纯白色也成灰色了 -->
        <img :src="qrCode.data" @load="qrCodeLoad" class="white-filter" v-show="!qrCodeLoading"/>
        <el-image style="width: 180px; height: 180px" v-show="qrCodeLoading">
          <div class="image-slot" slot="placeholder">
            <span class="el-icon-loading"></span>
          </div>
          <div class="image-slot" slot="error">
            <span class="el-icon-loading"></span>
          </div>
        </el-image>

        <div class="qrCode-help">使用
          <el-link type="primary">网易云音乐APP</el-link>
          登录
        </div>
        <div class="to-other-login-mode">
          <el-link @click.native.stop="toOtherLoginMode" type="info">选择其他登录模式></el-link>
        </div>
      </div>
      <!-- 网易邮箱登录 -->
      <div class="emailDialog" v-if="loginPage === 2">
        <div @click="loginPage = 0" class="email-title-tip">&lt;返回其他登录</div>
        <div class="login-box">
          <div class="email-img">
            <el-avatar :src="wyyyyIcon"
                       style="width: 100px; height: 100px; margin: 40px 0 20px;"></el-avatar>
          </div>
          <div class="email-form">
            <el-form :model="loginUser">
              <el-form-item>
                <el-input
                  placeholder="邮箱账号"
                  v-model="loginUser.email">
                  <template #prepend>
                    <el-icon>
                      <Iphone/>
                    </el-icon>
                  </template>
                </el-input>
              </el-form-item>
              <el-form-item>
                <el-input
                  placeholder="请输入密码"
                  v-model="loginUser.password">
                  <i class="el-input__icon el-icon-lock" slot="prefix"></i>
                  <template slot="append">
                    忘记密码 ?
                  </template>
                </el-input>
              </el-form-item>
              <el-form-item>
                <el-checkbox>
                  <span style="font-size: 12px">自动登录</span>
                </el-checkbox>
              </el-form-item>
              <el-form-item>
                <div style="margin-top: 30px; width: 100%">
                  <el-button @click="loginByEmail" style="width: 100%;" type="danger">
                    登录
                  </el-button>
                </div>
              </el-form-item>
            </el-form>
          </div>
        </div>
      </div>
    </el-dialog>
  </div>
</template>

<script lang="ts">
  import { loginApi } from '@/api/login'
  import { createNamespacedHelpers } from 'vuex'
  import wyyyyIcon from '@/assets/img/head.jpg'
  import { Iphone, Lock, Search } from '@element-plus/icons-vue'


  const { mapState, mapActions } = createNamespacedHelpers('user')

  const fixedSecond = 10
  export default {
    name: 'Login',
    inject: ['reload'],
    created() {
    },
    computed: {
      ...mapState(
        ['userProfile']
      )
    },
    data() {
      return {
        visible: false,
        Iphone,
        Search,
        Lock,
        wyyyyIcon,
        /** 0: 普通登录页, 1: 扫码登录页, 2: 邮箱登录页 */
        loginPage: 0,
        second: fixedSecond,
        /**
         * 是否倒计时
         * */
        isCountDown: false,
        /** qrCode是否在加载 */
        qrCodeLoading: true,
        loginUser: {
          email: 'wxzqs0103@163.com',
          phone: '18046750152',
          username: '18046750152',
          password: 'WxZqs-0103',
          code: '8894'
        },
        /**
         * 默认手机号登录
         * */
        isCodeLogin: true,
        qrCode: {
          unikey: '',
          data: '',
          // 定时器
          whileCodeCost: null
        }
      }
    },
    mounted() {
    },
    methods: {
      ...mapActions(['login']),
      qrCodeLoad() {
        this.qrCodeLoading = false
      },
      async createQrCode() {
        // 二维码登录才发送QrCode-Key请求
        if (this.loginPage === 1) {
          const { data: qrCodeKeyRes } = await loginApi().getQrCodeKey()
          const { data: createQrCodeRes } = await loginApi().createQrCode({
            key: qrCodeKeyRes.unikey,
            qrimg: true
          })
          this.qrCode.unikey = qrCodeKeyRes.unikey
          this.qrCode.data = createQrCodeRes.qrimg
          // 直到过期或扫码成功
          this.closeQrCodeInterval()
          this.qrCode.whileCodeCost = setInterval(async () => {
            try {
              const codeRes = await loginApi().selectQrCodeState({
                key: qrCodeKeyRes.unikey
              })
              // 二维码过期或者扫码成功
              if (codeRes.code === 800) {
                this.$notify({
                  title: '错误',
                  message: '二维码过期',
                  type: 'error'
                })
              }
              // 授权成功
              if (codeRes.code === 803) {
                console.log(codeRes)
                // 保存二维码下发的cookie
                this.saveUserCookie(codeRes.cookie)
                loginApi().getUserProfile().then(accountRes => {
                  this.saveUserData(accountRes)
                  this.login(accountRes)
                  this.closeLoginDialog()
                })

                this.$notify({
                  title: '成功',
                  message: '授权成功',
                  type: 'success'
                })
                this.reload()

              }

              if (codeRes.code === 800 || codeRes.code === 803) {
                this.closeQrCodeInterval()
              }
            } catch (e) {
              this.closeQrCodeInterval()
            }

          }, 1000)

        }
      },
      toQrCodePage() {
        this.loginPage = 1
        this.createQrCode()
      },
      toOtherLoginMode() {
        this.loginPage = 0
        // 关闭扫码定时器
        this.closeQrCodeInterval()
      },
      // 关闭二维码定时器
      closeQrCodeInterval() {
        if (this.qrCode.whileCodeCost) {
          clearInterval(this.qrCode.whileCodeCost)
        }
      },
      show() {
        console.log('show')
        console.log(this.isLogin)
        // 未登录才展示登录
        if (!this.isLogin) {
          this.visible = true
          if (this.loginPage === 1 && this.visible) {
            this.createQrCode()
          }
        }
      },
      /**
       * 手机号登录
       */
      loginByPhone() {
        loginApi().loginByPhone({
          phone: this.loginUser.phone,
          captcha: this.loginUser.code,
          password: this.loginUser.password
        }).then((res) => {
          console.log(window.storage.get('token'))
        })
      },
      /**
       * 匿名登录
       * */
      loginByAnonymous() {
        loginApi().loginByAnonymous().then((res) => {
          console.log(window.storage.get('token'))
        })
      },
      /**
       * 邮箱登录
       * */
      loginByEmail() {
        loginApi().loginByEmail({
          email: this.loginUser.email,
          password: this.loginUser.password
        }).then((res) => {
          this.saveUserData(res)
          this.saveUserCookie(res.cookie)
          // cookie与profile分开存储
          this.login(res)
          this.closeLoginDialog()
          this.$success('登录成功')
        })
      },
      /**
       * 关闭登录对话框
       * */
      closeLoginDialog() {
        this.visible = false
      },
      /**
       * 保存用户数据
       * */
      saveUserData(data) {
        window.storage.set('userData', data)
      },
      saveUserCookie(cookie) {
        window.storage.set('token', cookie)
      },
      /**
       * 验证码到邮箱 状态
       * */
      code2email() {
        this.isCodeLogin = !this.isCodeLogin
        console.log('验证码')
      },
      /**
       * 邮箱到验证码 状态
       * */
      email2code() {
        this.isCodeLogin = !this.isCodeLogin
        console.log('邮箱')
      },
      /**
       * 发送手机验证码
       * */
      sendCode() {
        this.isCountDown = true
        this.$success('发送验证码成功')
        loginApi().sendPhoneCode({
          phone: this.loginUser.phone
        }).then(() => {
          const countInterval = setInterval(() => {
            // 减少一秒
            this.second--
            if (this.second === 0) {
              this.isCountDown = false
              this.second = fixedSecond
              // 清除计时器
              clearInterval(countInterval)
            }
          }, 1000)
        })
      }

    }
  }
</script>

<style lang="less" scoped>

  .social-icons {
    width: 100%;
    display: flex;
    margin: 0 0 20px;
    justify-content: space-evenly;
  }

  .social-icon {
    cursor: pointer;
  }

  .spring {
    display: inline-block;
    vertical-align: middle;
    width: 38px;
    height: 38px;
    background: url(../../assets/img/spring.png) no-repeat 0 9999px;
  }

  .social-wx {
    background-position: -150px -670px;
  }

  .social-qq {
    background-position: -190px -670px;
  }

  .social-weibo {
    background-position: -231px -670px;
  }

  .social-163email {
    background-position: -271px -670px;
  }

  #qrcode-img {
    background-color: #fff;
  }

  .loginDialog {
    z-index: 10;
    display: flex;
    flex-direction: column;
    align-items: center;
  }

  .emailDialog {
    padding: 0 20px;
    height: 400px;
    display: flex;
    flex-direction: column;
    align-items: center;
  }

  .email-form {
    padding: 20px 0;
  }

  .email-img {
    text-align: center;
  }

  .login-box {
    max-width: 270px;
  }

  .login-box-center {
    display: flex;
    flex-direction: column;
    align-items: center;
  }

  .email-title-tip {
    cursor: pointer;
    position: absolute;
    top: 20px;
    left: 10px;
    font-size: 12px;
  }

  .qrCodeDialog {
    text-align: center;
  }

  .forget-login {
    font-size: 12px;
  }

  .login-form-summary {
    margin: 20px 0 10px;
    text-decoration-line: underline;
    display: flex;
    align-items: center;
    justify-content: center;
  }

  .qrCode {
    cursor: pointer;
    padding: 0;
    width: 52px;
    height: 52px;
    transform: rotate(180deg);
    top: 0;
    left: 0;
    position: absolute;
  }

  .terms-service {
    font-size: 13px;
    display: flex;
    justify-content: center;
    align-items: center;
    white-space: nowrap;
  }

  .terms-service-text {
    font-size: 13px;
    white-space: nowrap;
  }

  .login-form {
    margin: 20px 0;
  }

  .page {
    position: relative;
    margin-left: 0;
    filter: drop-shadow(0px 0px 15px #bbb);
  }

  .login-dialog {
    padding: 0;
    border-radius: 0;
  }

  :deep(.el-dialog__body) {
    padding: 0;
    padding-bottom: 20px;
  }

  :deep(.el-form-item) {
    margin-bottom: 0;
  }

  .qrcode-text {
    margin: 60px 0 30px;
    font-size: 30px;
    color: black;
  }

  .image-slot {
    position: absolute;
    left: 50%;
    top: 50%;
    transform: translate(-50%, -50%);
  }

  .qrcode-img {
  }

  .white-filter {
    /* 去除滤镜 */
    filter: none;
    -webkit-filter: none;
  }

  .qrCode-help {
    padding-top: 20px;
    display: flex;
    justify-content: center;
  }

  .to-other-login-mode {
    padding: 60px 0 30px;
  }
</style>
